package com.workingpub.commons.utils.jmx;

import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * JMX MBean基类，实现初始化和销毁方法
 * 
 * @author taoping
 *
 */
public abstract class MBeanSuport {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private ObjectName objectName;
	private ObjectInstance objectInstance;
	private MBeanServer mbeanServer;

	public void init() throws Exception {
		if (null == objectName) {
			String mbeanName = getDefaultObjectName();
			Assert.isTrue(StringUtils.hasText(mbeanName), "The default object name cannot be empty or null.");
			objectName = new ObjectName(mbeanName);
		}
		if (null == mbeanServer) {
			mbeanServer = ManagementFactory.getPlatformMBeanServer();
		}
		if (!mbeanServer.isRegistered(objectName)) {
			objectInstance = mbeanServer.registerMBean(this, objectName);
			logger.info("Success to register mbean : " + objectName);
		} else {
			logger.info("This mbean is already registered : {}", objectName);
		}
	}

	public void destory() throws Exception {
		if (isRegistered()) {
			mbeanServer.unregisterMBean(objectName);
			logger.info("Success to unregister mbean : {}", objectName);
		} else {
			logger.info("This mbean is not exist : {}", objectName);
		}
	}

	protected abstract String getDefaultObjectName();

	public ObjectName getObjectName() {
		return objectName;
	}

	public ObjectInstance getObjectInstance() {
		return objectInstance;
	}

	public MBeanServer getMbeanServer() {
		return mbeanServer;
	}

	public boolean isRegistered() {
		if (null == objectName || null == mbeanServer) {
			return false;
		} else {
			return mbeanServer.isRegistered(objectName);
		}
	}

}
